package org.yufan.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.yufan.bean.User;
import org.yufan.exception.CustomerException;
import org.yufan.mapper.UserMapper;
import org.yufan.service.JedisService;
import org.yufan.service.UserService;
import org.yufan.utils.JsonUtils;

import java.util.Date;
import java.util.UUID;

@Service
@Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,readOnly = false)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JedisService jedisService;

    private static final String USER_LOGIN="gfsdgvafvqweac:";

    private Logger LOGGER=LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public void register(User user) throws CustomerException {
        if(user==null){
            LOGGER.info("用户信息为空");
            return;
        }
        //1.用户名 电话 邮箱不能重复
        if(queryByPhone(user.getPhone())!=null){
            //电话号码已经注册
            LOGGER.info("电话号码已经注册了{}",user.getPhone());
            throw  new CustomerException("电话号码已经注册了!");
        }
        if(queryByEmail(user.getEmail())!=null){
            //电话号码已经注册
            LOGGER.info("邮箱已经注册了{}",user.getEmail());
            throw  new CustomerException("邮箱已经注册了!");
        }
        if(queryByUsername(user.getUsername())!=null){
            //电话号码已经注册
            LOGGER.info("用户名已经注册了{}",user.getUsername());
            throw  new CustomerException("用户名已经注册了!");
        }

        //2.加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setCreated(new Date());
        user.setUpdated(user.getCreated());

        //3.保存
        userMapper.insertSelective(user);
    }

    public User queryByPhone(String phone) {
       User record=new User();
       record.setPhone(phone);
       return userMapper.selectOne(record);
    }

    private User queryByUsername(String username) {
        User record=new User();
        record.setUsername(username);
        return userMapper.selectOne(record);
    }

    private User queryByEmail(String email) {
        User record=new User();
        record.setEmail(email);
        return userMapper.selectOne(record);
    }

    @Override
    public String login(String username, String password) throws CustomerException {
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
           LOGGER.info("参数为空!");
            throw  new CustomerException("参数为空!");
        }
        //密码加密
        User record=new User();
        record.setUsername(username);
        record.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        User user = userMapper.selectOne(record);
        if(user==null){
            LOGGER.info("用户名密码错误:{}",username);
            throw  new CustomerException("用户名密码错误!");
        }
        return getToken(user);

    }

    public String getToken(User user) {
        //处理登录
        String token=getToken();
        //设置登录信息到redis服务器
        jedisService.set(USER_LOGIN+token,JsonUtils.objectToJson(user));
        //设置失效时间
        jedisService.expire(USER_LOGIN+token,60*60*2);
        return token;
    }

    @Override
    public String loginByPhone(String phone, String code) throws CustomerException {
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(code)){
            LOGGER.info("手机号码和验证码不能为空");
            return null;
        }
        String service_code=jedisService.get(SmsServiceImpl.SMS_LOGIN+phone);
        if(StringUtils.isEmpty(service_code)){
            LOGGER.info("验证码失效!手机号码{}",phone);
            throw new CustomerException("验证码失效，请重新发送短信!");
        }
        if(!service_code.equals(code)){
        LOGGER.info("手机号码{},验证码输入错误,验证码{}",phone,code);
        throw new CustomerException("验证码输入错误!");
        }
       User user=queryByPhone(phone);
        if(user==null){
        LOGGER.info("该手机号码{}，未注册",phone);
        throw  new CustomerException("手机号码未注册!");
        }
        return getToken(user);
}

    /**
     * 生成令牌
     * @return
     */
    public String getToken(){
       String uuid= UUID.randomUUID().toString();
       return DigestUtils.md5DigestAsHex(uuid.getBytes());
    }

    @Override
    public User queryUserByToken(String token) throws CustomerException {
        if(StringUtils.isEmpty(token)){
            throw  new CustomerException("token不能为空");
        }
        LOGGER.info("当前查询用户信息的token为{}",token);
        String json=jedisService.get(USER_LOGIN+token);
        if(StringUtils.isEmpty(json)){
            LOGGER.info("登录失效!,token为{}",token);
            return null;
        }
        //刷新失效时间
        jedisService.expire(USER_LOGIN+token,60*60*2);
        return JsonUtils.jsonToPojo(json,User.class);
    }



}
